/**
 * 数据处理相关功能 Composable
 * 包含不同模式的数据处理、提交等功能
 */
import { ref, reactive, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { planAdd, updatePlan } from '../api/RoutePlan'
import { toLatLng } from "../assets/cesiumFunction/Map"

export function useDataProcessing() {
  const router = useRouter()
  const route = useRoute()
  
  // 响应式数据
  const editName = ref(false)
  const uavTaskName = ref('')
  const recordList = ref([])
  const areaRecord = ref([])
  const lineRecord = ref([])
  const uavLinesInfoList = ref([
    ['航线总长度', '0 m'],
    ['航线模式', ''],
    ['航线高度', '0 m'],
    ['航点数量', '0 个'],
    ['飞行点数', '0个'],
    ['预计飞行时间', '0 s']
  ])
  
  const modeNameOption = reactive({
    0: '逐点飞行',
    1: '区域飞行',
    2: '3D区域飞行'
  })

  /**
   * 保存航线任务
   */
  const saveRoutePlan = async (settingRef) => {
    const routeData = JSON.parse(route.query.data)
    editName.value = false

    let body = null
    // 根据当前模式处理数据
    switch (route.query.mode) {
      case '0':
        body = processPointData(settingRef)
        break
      case '1':
        body = processAreaData(settingRef)
        break
      case '2':
        body = process3DAreaData(settingRef)
        break
      case '3':
        body = processLineData(settingRef)
        break
      case '4':
        body = processBuildingData(settingRef)
        break
    }

    try {
      if (routeData.wayline_id == 'new' || routeData.wayline_id == 'loadMap') {
        
        const reply = await planAdd(body)
        if (reply.code == 0) {
          ElMessage.success('保存成功:' + reply.message)
          clear()
          // 使用 nextTick 和 setTimeout 确保组件完全卸载后再跳转
          await nextTick()
          setTimeout(async () => {
            await router.push({
              path: "/uavtask",
            })
          }, 100)
        } else {
          ElMessage.error(reply.message)
        }
        console.log('新建任务返回：', reply)
      } else {
        body['wayline_id'] = routeData.wayline_id
        const reply = await updatePlan(body)
        if (reply.code == 0) {
          ElMessage.success('保存成功:' + reply.message)
          clear()
          // 使用 nextTick 和 setTimeout 确保组件完全卸载后再跳转
          await nextTick()
          setTimeout(async () => {
            await router.push({
              path: "/uavtask",
            })
          }, 100)
        } else {
          ElMessage.error(reply.message)
        }
        console.log('更新任务返回:', reply)
      }
    } catch (error) {
      console.error('保存任务失败:', error)
      ElMessage.error('保存失败，请重试')
    }
  }

  /**
   * 处理逐点数据
   */
  const processPointData = (settingRef) => {
    let setting = settingRef
    if (recordList.value) {
      const takeoffPoint = {
        "longitude": recordList.value[0].point_coordinate.longitude,
        "latitude": recordList.value[0].point_coordinate.latitude,
        "altitude": setting.height,
      }
      
      let postDataJson = {
        "wayline_id": "",
        "wayline_name": uavTaskName.value,
        "author": "",
        "create_time": 0,
        "update_time": 1748094056544,
        "mission_config": {
          "finish_action": 0,
          "take_off_ref_point": takeoffPoint,
          "drone_type": 100,
          "drone_sub_type": 1,
          "payload_type": 99,
          "payload_sub_type": 0
        },
        "wayline_folder": {
          "template_type": 0,
          "global_speed": setting.linesSpeedOption,
          "height_mode": 0,
          "camera_lens_type": setting.cameraType,
          "global_height": setting.height,
          "global_waypoint_turn_mode": 2,
          "gimbal_pitch_mode": 2,
          "waypoint_heading_mode": 0,
          "uav_positions": recordList.value,
        },
        "display_wayline": {
          "fly_points": [],
        },
      }
      return postDataJson
    }
  }

  /**
   * 处理区域数据
   */
  const processAreaData = (settingRef) => {
    let setting = settingRef
    let areaSetting = settingRef
    let polygonPoints = []
    
    areaRecord.value.map((item) => {
      let polygonPoint = toLatLng(item)
      polygonPoint['altitude'] = 0
      polygonPoints.push(polygonPoint)
    })
    
    let take_off_point = toLatLng(areaRecord.value[0])
    take_off_point['altitude'] = setting.height
    
    let postDataJson = {
      "wayline_id": "",
      "wayline_name": uavTaskName.value,
      "workspace_id": "",
      "author": "",
      "create_time": 0,
      "update_time": 0,
      "mission_config": {
        "finish_action": 0,
        "take_off_ref_point": take_off_point,
        "drone_type": 100,
        "drone_sub_type": 1,
        "payload_type": 99,
        "payload_sub_type": 0
      },
      "wayline_folder": {
        "template_type": 1,
        "global_speed": setting.linesSpeedOption,
        "height_mode": 0,
        "camera_lens_type": areaSetting.cameraType,
        "elevation_optimize_enable": 1,
        "shoot_type": 0,
        "direction": 199,
        "margin": 0,
        "facade_wayline_enable": 0,
        "global_height": setting.height,
        "ground_height": 29,
        "overlap_height": setting.height - 29,
        "overlap_width": areaSetting.overlapWidth,
        "overlap_height": areaSetting.overlapHeight,
        "polygon": polygonPoints,
      },
      "display_wayline": {
        "fly_points": [],
      },
    }
    console.log("要上传的信息-初步", postDataJson)
    return postDataJson
  }

  /**
   * 处理3D区域数据
   */
  const process3DAreaData = (settingRef) => {
    let setting = settingRef
    let areaSetting = settingRef
    let polygonPoints = []
    
    areaRecord.value.map((item) => {
      let polygonPoint = toLatLng(item)
      polygonPoints.push(polygonPoint)
    })
    
    let take_off_point = toLatLng(areaRecord.value[0])
    take_off_point['altitude'] = setting.height
    
    let postDataJson = {
      "wayline_id": "",
      "wayline_name": uavTaskName.value,
      "workspace_id": "",
      "author": "",
      "create_time": 0,
      "update_time": 0,
      "mission_config": {
        "finish_action": 0,
        "take_off_ref_point": take_off_point,
        "drone_type": 100,
        "drone_sub_type": 1,
        "payload_type": 99,
        "payload_sub_type": 0
      },
      "wayline_folder": {
        "template_type": 1,
        "global_speed": setting.linesSpeedOption,
        "height_mode": 0,
        "camera_lens_type": areaSetting.cameraType,
        "elevation_optimize_enable": 1,
        "shoot_type": 0,
        "direction": 199,
        "margin": 0,
        "facade_wayline_enable": 1,
        "global_height": setting.height,
        "ground_height": 29,
        "overlap_height": setting.height,
        "overlap_width": areaSetting.overlapWidth,
        "overlap_height": areaSetting.overlapHeight,
        "polygon": polygonPoints,
      },
      "display_wayline": {
        "fly_points": [],
      },
    }
    console.log("要上传的信息-初步", postDataJson)
    return postDataJson
  }

  /**
   * 处理沿线数据
   */
  const processLineData = (settingRef) => {
    let setting = settingRef
    let lineSetting = settingRef
    const firstPoint = lineRecord.value[0]
    let take_off_point = toLatLng(firstPoint)
    let linePoints = []
    lineRecord.value.map((item) => {
      let linePoint = toLatLng(item)
      linePoints.push(linePoint)
    })


    let postDataJson = {
      "wayline_id": "",
      "wayline_name": uavTaskName.value,
      "workspace_id": "",
      "author": "",
      "create_time": 0,
      "update_time": 0,
      "mission_config": {
        "finish_action": 0,
        "take_off_ref_point": take_off_point,
        "drone_type": 100,
        "drone_sub_type": 1,
        "payload_type": 99,
        "payload_sub_type": 0
      },
      "wayline_folder": {
        "template_type": 3,
        "global_speed": setting.linesSpeedOption,
        "height_mode": 0,
        "camera_lens_type": lineSetting.cameraType,
        "elevation_optimize_enable": 0,
        "shoot_type": 0,
        "global_height": setting.height,
        "single_line": 0,//单航线模式（仅折线飞），0不开启，1开启
        "cutting_distance": 2000.0,//每个子条带长度
        "ground_height": 29,
        "overlap_width": lineSetting.overlapWidth,
        "overlap_height": lineSetting.overlapHeight,
        "line_string": linePoints,
        "left_extend": lineSetting.buffer,
        "right_extend": lineSetting.buffer,
      },
      "display_wayline": {
        "fly_points": [],
      }
    }
    return postDataJson
  }

  const processBuildingData = (settingRef) => {
    let setting = settingRef
    let areaSetting = settingRef
    let polygonPoints = []
    
    areaRecord.value.map((item) => {
      let polygonPoint = toLatLng(item)
      polygonPoint['altitude'] = 0
      polygonPoints.push(polygonPoint)
    })
    
    let take_off_point = toLatLng(areaRecord.value[0])
    take_off_point['altitude'] = setting.height
    
    let postDataJson = {
      "wayline_id": "",
      "wayline_name": uavTaskName.value,
      "workspace_id": "",
      "author": "",
      "create_time": 0,
      "update_time": 0,
      "mission_config": {
        "finish_action": 0,
        "take_off_ref_point": take_off_point,
        "drone_type": 100,
        "drone_sub_type": 1,
        "payload_type": 99,
        "payload_sub_type": 0
      },
      "wayline_folder": {
        "template_type": 4,
        "global_speed": setting.linesSpeedOption,
        "height_mode": 0,
        "camera_lens_type": areaSetting.cameraType,
        "elevation_optimize_enable": 1,
        "shoot_top_face_enable": 1,//是否拍摄几何体顶部
        "overlap_height": 70,////纵向重叠率，航行方向
        "overlap_width": 70,//横向重叠率，航行侧向方向
        "shoot_type": 0,//等时拍照，1等距拍照
        "trajectory_type": 0,//水平绕几何体飞行，默认不需要修改
        "start_position_type": 0,//从底部开始飞行，默认不需要修改
        "prism_height": setting.prismHeight,
        "shoot_height": 35.0,//距离几何体拍摄的距离
        "scan_extent": setting.roundNum,//几何体周边覆盖度，100即为绕一圈，50即为绕半圈
        "scan_offset": 83.9,//航点起点相对起飞点偏移的角度，逆时针旋转，从0到360度，与scan_extent配合可以绕飞几何体特定侧面
        "top_flight_speed": 10.742454,//顶部飞行速度
        "polygon": polygonPoints,
      },
      "display_wayline": {
        "fly_points": [],
      }
    }

    return postDataJson
  }

  /**
   * 更新航线信息
   */
  const refreshLineInfo = (list) => {
    const pointList = JSON.parse(JSON.stringify(list))
    console.log(pointList)
    let allDistance = 0
    
    if (pointList.length > 1) {
      for (var i = 0; i < pointList.length - 1; i++) {
        let startPoint = Cesium.Cartesian3.fromDegrees(pointList[i].point_coordinate.longitude, pointList[i].point_coordinate.latitude, 100)
        let endPoint = Cesium.Cartesian3.fromDegrees(pointList[i + 1].point_coordinate.longitude, pointList[i + 1].point_coordinate.latitude, 100)
        let distance = Cesium.Cartesian3.distance(startPoint, endPoint)
        allDistance += distance
      }
    }
    uavLinesInfoList.value[0][1] = allDistance.toFixed(2) + ' m'
    uavLinesInfoList.value[3][1] = pointList.length + ' 个'
  }

  /**
   * 更新区域信息
   */
  const refreshAreaInfo = (list) => {
    const pointList = JSON.parse(JSON.stringify(list))
    console.log(pointList, list)
    uavLinesInfoList.value[3][1] = pointList.length + ' 个'
  }

  /**
   * 初始化航线信息列表
   */
  const initUavLinesInfoList = (routeData) => {
    uavLinesInfoList.value[0][1] = '0 m'
    uavLinesInfoList.value[1][1] = modeNameOption[routeData.wayline_folder.template_type]
    uavLinesInfoList.value[2][1] = '0 m'
    uavLinesInfoList.value[3][1] = routeData.wayline_folder.uav_positions ? 
      routeData.wayline_folder.uav_positions.length + ' 个' : 
      routeData.wayline_folder.polygon.length + ' 个'
    uavLinesInfoList.value[4][1] = routeData.display_wayline.fly_points.length + '个'
    uavLinesInfoList.value[5][1] = '0 s'
  }

  /**
   * 清空数据
   */
  const clear = () => {
    recordList.value = []
    areaRecord.value = []
    uavTaskName.value = ''
    editName.value = false
  }

  return {
    // 响应式数据
    editName,
    uavTaskName,
    recordList,
    areaRecord,
    lineRecord,
    uavLinesInfoList,
    modeNameOption,
    
    // 方法
    saveRoutePlan,
    processPointData,
    processAreaData,
    process3DAreaData,
    refreshLineInfo,
    refreshAreaInfo,
    initUavLinesInfoList,
    clear
  }
}
